import { defineStore } from "pinia";
import {userApi} from '@/api/user.ts'
import {
  getToken,setToken,removeToken,getDeviceInfo,setDeviceInfo,removeDeviceInfo,getBasebandInfo,setBasebandInfo,
  getBtnPermissions,setBtnPermissions,removeBtnPermissions,removeBasebandInfo
} from '@/utils/token-utils.ts'
import router from '@/router'
import { allAsyncRoutes,staticRoutes,anyRouter} from "@/router/routes";
import type { RouteRecordRaw } from "vue-router";
import cloneDeep from 'lodash/cloneDeep'
import { BasebandApi} from "@/api/basebandControl";
/* function filterUserRoutes(allAsyncRoutes: RouteRecordRaw[], userRoutes: string[]): RouteRecordRaw[] {
    return allAsyncRoutes.filter(item => {
      const match = userRoutes.find((userItem: any) => userItem == item.name);
      if (match) {
        if (item.children && item.children.length) {
          item.children = filterUserRoutes(item.children, userRoutes);
        }
        return true;
      }
      return false;
    });
  } */

function addUserAsyncRoutes(userAsyncRoutesAndAnyRoute:RouteRecordRaw[]){
    userAsyncRoutesAndAnyRoute.forEach(item=>{
      router.addRoute(item)
    })
}
  
function clearRoutes(){
    let routes = router.getRoutes()
    routes.forEach(item=>{
      router.removeRoute(item.name as string)
    })
    addUserAsyncRoutes(staticRoutes)
}
function filterUserRoutes(allAsyncRoutes: RouteRecordRaw[], userRole:string){
  let userRoutes:RouteRecordRaw[] = []
  if(userRole === "user"){
    const networkAccessManagement = allAsyncRoutes.find(item=>item.name === "RootNetworkAccessManagement")
    if (networkAccessManagement) {
      userRoutes = [networkAccessManagement]
    } else {
      userRoutes = []
    }
  }else{
    userRoutes = allAsyncRoutes
  }
  return userRoutes
}

function generateBtnPermissions(userRole:string){
  let btnPermissions:string[] = []
  if(userRole === "user"){
    btnPermissions = []
  }else{
    btnPermissions = ["freqDelete","freqEdit","freqAdd"]
  }
  return btnPermissions
}

interface UserData{
  token:string | null,
  menus: RouteRecordRaw[],
  userInfo:{
    username:string
  },
  [key: string]: any,
  deviceType:number | string,
  basebandNum:number,
  currentCpId:string | number,
  btnPermissions:string[]
}
/**
 * 获取用户信息
 * @returns 
 * @deviceType 设备类型 0:0.6高轨 1:机载高轨 2:机载低轨
 * @basebandNum 基带数量
 * @btnPermissions  用户按钮权限
 */
const getUserData = ():UserData=>{
  return {
    token:getToken(),
    menus:[],
    userInfo:{
      username:""
    },
    deviceType:getDeviceInfo() || 0,
    basebandNum:getBasebandInfo()?.basebandNum || 0,
    currentCpId:getBasebandInfo()?.currentCpId!==undefined?getBasebandInfo()?.currentCpId:'',
    btnPermissions:getBtnPermissions() || []
  }
}

export const useUserInfoStore = defineStore("userInfo", {
    state:()=>{
        return getUserData()
    },
    actions:{
        async login(loginParams:any){
            try {
              const res = await userApi.login(loginParams)
              const{ token} = res.data
              setToken(token)
              this.token = token
              return "ok";
            } catch (error) {
                return Promise.reject("fail");
            }
        },
        async getUserInfo(){
          try {
          const res:any =await userApi.reqGetUserInfo()
          const {username,userrole} = res.data
          this.userInfo.username = username
          let useAsyncRoutes = filterUserRoutes(cloneDeep(allAsyncRoutes),userrole)
          addUserAsyncRoutes(useAsyncRoutes.concat(staticRoutes,anyRouter))
          this.menus = staticRoutes.concat(useAsyncRoutes,anyRouter)
          this.btnPermissions = generateBtnPermissions(userrole)
          setBtnPermissions(this.btnPermissions)
          return "ok";
          } catch (error) {
          return Promise.reject(error);      
          }
        },
        reset(){
          removeToken()  
          removeDeviceInfo()
          removeBasebandInfo()
          removeBtnPermissions()
          const defaultData:UserData = getUserData();
          Object.keys(defaultData).forEach((key) => {
            this[key] = defaultData[key];
          });  
        },

        async loginOut(){
          try {
          // await userApi.loginOut()   
          this.reset();
          clearRoutes()
          } catch (error) {    
          return Promise.reject("fail");           
          }
      },
      async getDeviceInfo(){
        try {
          const {data}:any = await userApi.getDeviceInfo()
          this.deviceType = data.device_type
          setDeviceInfo(this.deviceType)
        } catch (error) {
          return Promise.reject(error);
        }
      },
      async getBasebandInfo(){
        try {
          const {data:{info}}:any = await BasebandApi.reqGetBasebandInfo()
          this.basebandNum = info.length
          if(info.length>0){
            this.currentCpId = info[0].id
          }
          setBasebandInfo({
            basebandNum:this.basebandNum,
            currentCpId:this.currentCpId
          })
          return "ok"
        } catch (error) {
          return Promise.reject(error);
        }
      }
    }
})